import { DictArray } from "../utils/array.util"
import EventObserverAdaptor from "./EventObserverAdaptor"
import EventSubscribeMessage from "./EventSubscribeMessage"
import EventUnsubscribeMessage from "./EventUnsubscribeMessage"

export default class EventInterfaceBuilder {
  messenger: any
  eventHandlers: any
  eventObserver: any
  constructor(t) {
    ;(this.messenger = t), (this.eventHandlers = new DictArray())
    const e = new (class EventFacade {
      eventHandler: any
      constructor(t) {
        this.eventHandler = t
      }
      receiveEvent(t) {
        this.eventHandler.receiveEvent(t)
      }
    })(this)
    ;(this.eventObserver = new EventObserverAdaptor(e)), this.messenger.addObserver(this.eventObserver)
  }
  build() {
    return { on: (t, e) => this.subscribe(t, e), off: (t, e) => this.unsubscribe(t, e) }
  }
  dispose() {
    for (const t of this.eventHandlers.keys) this.messenger.send(new EventUnsubscribeMessage(t))
    this.messenger.removeObserver(this.eventObserver)
  }
  receiveEvent(t) {
    const e = this.eventHandlers.getValuesAtKey(t.eventType)
    if (e) for (const s of e) t.eventData ? s(...t.eventData) : s()
  }
  subscribe(t, e) {
    0 === this.eventHandlers.valuesPerKey(t) && this.messenger.send(new EventSubscribeMessage(t)), this.eventHandlers.add(t, e)
  }
  unsubscribe(t, e) {
    this.eventHandlers.remove(t, e), 0 === this.eventHandlers.valuesPerKey(t) && this.messenger.send(new EventUnsubscribeMessage(t))
  }
}
